﻿#include "Channels.h"

#include <event2/bufferevent.h>

Channel::Channel(const ChannelCreateInfo* i) : info{ *i }, state{ CHANNEL_STATE_UNSTART }
{
	if(info.type & CHANNEL_PROTO_TYPE_FILE)
	{

	}
}

const char* TCPServerChannel::get_proto_name()
{
	if(info.type & CHANNEL_PROTO_TYPE_FILE)
	{
		return "文件传输";
	}
	return "TCP服务端通道";
}

const char* TCPClientChannel::get_proto_name()
{
	if(info.type & CHANNEL_PROTO_TYPE_FILE)
	{
		return "文件传输";
	}
	return "TCP客户端通道";
}

const char* UDPChannel::get_proto_name()
{
	if(info.type & CHANNEL_PROTO_TYPE_FILE)
	{
		return "文件传输";
	}
	return "UDP通道";
}

size_t Channel::ReadData(read_buffer_cache& cache)
{
	return ReadDataImpl(cache);
}

void Channel::SendData(read_buffer_cache& cache)
{}

USHORT Channel::get_local_port()
{
	return ntohs(info.input_address.addr.sin_port);
}

ChannelCreateInfo& Channel::get_info()
{
	return info;
}

size_t TCPServerChannel::ReadDataImpl(read_buffer_cache& cache)
{
	return 0;
}

void TCPServerChannel::add_client(bufferevent* sub)
{
	std::lock_guard<std::mutex> lg{ clients_mutex };
	auto fd = bufferevent_getfd(sub);
	SocketAddress sa{};
	auto len = sa.len();
	getsockname(fd, sa.get(), &len);
	clients.push_back({ sub ,sa.addr });
}

void TCPServerChannel::del_client(bufferevent* sub)
{
	std::lock_guard<std::mutex> lg{ clients_mutex };
	for(auto& item : clients)
	{
		if(item.first == sub)
		{
			item = clients.back();
			clients.pop_back();
			break;
		}
	}
}

MollacDB::MollacDB(size_t size)
{
	len = size;
	data_ptr = ::malloc(size);
}

void* MollacDB::data()
{
	return data_ptr;
}

void MollacDB::free()
{
	::free(data_ptr);
}
